package com.tuling.spring;

import com.tuling.UserInterface;
import com.tuling.UserService;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * 将代理对象直接注册成Spring bean
 * 缺点：{@link ProxyFactoryBean#setTarget(Object)}要明确具体的被代理对象
 */
public class ProxyFactoryBeanDemoA {
	@Bean
	public ProxyFactoryBean userServiceProxy() {
		UserService userService = new UserService();

		ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
		proxyFactoryBean.setTarget(userService);
		proxyFactoryBean.addAdvice((MethodInterceptor) invocation -> {
			System.out.println("before...");
			Object result = invocation.proceed();
			System.out.println("after...");
			return result;
		});
		return proxyFactoryBean;
	}

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProxyFactoryBeanDemoA.class);
		UserInterface userInterface = (UserInterface) context.getBean("userServiceProxy");
		userInterface.test();
	}
}
